package com.woniu.woniuk16.securityUtil;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniu.woniuk16.dto.WoniuUserDetails;
import com.woniu.woniuk16.mapper.WoniuResourceMapper;
import com.woniu.woniuk16.model.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.annotation.Resource;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

public class LoginSuccessHandler implements AuthenticationSuccessHandler {
    //MVC自带的JSON序列化工具对象
    private ObjectMapper om = new ObjectMapper();

    @Resource
    private WoniuResourceMapper woniuResourceMapper;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication)
            throws IOException, ServletException {
        //得到登录成功之后的账号信息对象
        WoniuUserDetails wd = (WoniuUserDetails)authentication.getPrincipal();
        wd.setAccountPass(null);

        //设置json响应
        response.setCharacterEncoding("utf8");
        response.setContentType("application/json;charset=utf8");
        //构建Result
        Result result = Result.getInstance(wd).setMessage("登陆成功");

        //把result序列化成JSON字符串
        String json = om.writeValueAsString(result);
        //响应
        response.getWriter().write(json);
        response.getWriter().flush();
    }



}
